package com.pmcc.core.web;

import java.util.*;
import java.util.stream.Collectors;

import com.pmcc.core.config.exception.ForbiddenException;
import com.pmcc.core.config.security.JwtUser;
import com.pmcc.core.config.utils.AntPageRequest;
import com.pmcc.core.dto.ApiResult;
import com.pmcc.core.dto.EmployeeMyself;
import com.pmcc.core.dto.EmployeePermission;
import com.pmcc.core.entity.User;
import com.pmcc.core.entity.security.Employee;
import com.pmcc.core.entity.security.Organization;
import com.pmcc.core.entity.security.Role;
import com.pmcc.core.enums.State;
import com.pmcc.core.repository.EmployeeRepository;
import com.pmcc.core.repository.RoleRepository;
import com.pmcc.core.service.EmployeeService;
import com.pmcc.utils.*;
import com.pmcc.core.vo.EmployeeVo;
import com.pmcc.utils.ResultBean;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.QueryByExampleExecutor;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.pmcc.core.config.security.JwtTokenUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by tomas on 18/4/9.
 */
@RestController()
@RequestMapping("api/v1/employees")
@Api(value = "EmployeeController", description = "人员管理权限")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private EmployeeRepository employeeRepository;


    @ApiOperation(value = "分页查询", httpMethod = "GET", notes = "人员列表", response = ResultBean.class)
    @GetMapping(value = "queryByPage")
    public ResultBean queryByPage(@ApiParam(required = false, name = "分页显示", value = "分页参数，默认第一页10条数据")AntdPage antdPage,
                                  @ApiParam(required = false, name = "实体对象", value = "实体参数")Employee model){
       return employeeService.queryByPage(antdPage,model);
    }


    /**
     * 新增
     * @param employee
     * @return
     */
    @ApiOperation(value = "新增", httpMethod = "POST", notes = "新增人员", response = ResultBean.class)
    @PostMapping(value = "addEmployee")
    public ResultBean addEmployee(@ApiParam(required = true, name = "实体对象" ,value = "实体参数")@RequestBody Employee employee){
        return employeeService.addEmployee(employee);
    }

    /**
     * 按机构编号查询人员
     * @param code
     * @return
     */
    @ApiOperation(value = "查询", httpMethod = "GET", notes = "按机构编号查询", response = ResultBean.class)
    @GetMapping(value = "queryByCode")
    public ResultBean queryById(@ApiParam(required = false, name = "分页显示", value = "分页参数，默认第一页10条数据")AntdPage antdPage,
                                @ApiParam(required = true,name = "以code模糊查询", value = "必须传输code")String code){
        return employeeService.queryByCode(antdPage,code);
    }

    /**
     * 修改
     * @param map
     * @return
     */
    @ApiOperation(value = "修改保存", httpMethod="PUT", notes = "保存修改人员信息", response = ResultBean.class)
    @PutMapping("updateById")
    public ResultBean edit(@ApiParam(required =true, name ="人员信息", value ="必须传输id")@RequestBody Map map) {
        return employeeService.update(map);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ApiOperation(value = "id", httpMethod="GET", notes = "假删除人员信息", response = ResultBean.class)
    @GetMapping("deleteById")
    public ResultBean delete(@ApiParam(required =true, name ="假除人员信息", value ="id")String id) {
        return employeeService.deleteById(id,1);
    }

    /**
     * 获取登录人信息
     *
     * @param request
     * @return
     */
    @GetMapping(value = "getEmployeeInfo")
    public User getEmployeeInfo(HttpServletRequest request){
        String token=request.getHeader("token");
        return employeeService.getEmployeeInfo(token);
    }


    /**
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/loginOut")
    public ResultBean getLoginOut(HttpServletRequest request, HttpServletResponse response) {
        String authToken=request.getHeader("token");

        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        //当前登录人
        Employee employee = employeeRepository.findById(jwtTokenUtil.getUserIdFromToken(authToken));
        Cookie[] cookies = request.getCookies();
        String token = "";
        if (null == cookies) {
            System.out.println("没有cookie==============");
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    System.out.println("被删除的cookie名字为:" + cookie.getName());
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        return resultBean;
    }

    @PostMapping(value = "resetPassword")
    public ResultBean resetPassword(@RequestBody Map<String,String> map,HttpServletRequest request){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        String token=request.getHeader("token");
        String username = jwtTokenUtil.getUsernameFromToken(token);
        Employee employee = employeeRepository.findByUserName(username);
        String password=map.get("password").toString();//获取输入的密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(encoder.matches(password,employee.getPassword())){
        String newPassword=map.get("newPassword").toString();//获取新输入的密码
        employee.setPassword(encoder.encode(newPassword));
        employeeRepository.save(employee);
        resultBean.setResultDesc("修改成功!");
    }else{
        resultBean.setResultCode(ResultBean.FAIL);
        resultBean.setResultDesc("原密码输入不正确!");
    }
            return resultBean;
}

    @PostMapping("/resetPwd")
    public ResultBean rePwdEmp(@RequestBody  Employee employee){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        employeeService.restPwd(employee);
        return resultBean;
    }

    @ApiOperation(value = "更新个人信息", httpMethod="POST",notes = "更新个人信息", response = ResultBean.class)
    @PostMapping("updateButton")
    public ResultBean updateButton(@ApiParam(required =true, name ="对象", value ="除ID以外的实体参数")@RequestBody User user) throws Exception{
        return employeeService.updateButton(user);
    }

    /**
     * 用户头像上传
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "file", httpMethod="POST", notes = "单个上传", response = String.class)
    public String upload(@RequestParam("file") MultipartFile file,String employeeId) {
        return  employeeService.upload(file,employeeId);
    }
    /**
     * 修改密码
     */
    @ApiOperation(value = "id", httpMethod="GET", notes = "修改密码", response = ResultBean.class)
    @GetMapping("saveNewPwd")
    public ResultBean saveNewPwd(@ApiParam(required =true, name ="修改密码", value ="userId")String userId,String newPwd) {
        return employeeService.saveNewPwd(userId,newPwd);
    }
    /**
     * 修改手机密保
     */
    @ApiOperation(value = "id", httpMethod="GET", notes = "修改手机密保", response = ResultBean.class)
    @GetMapping("saveNewPhone")
    public ResultBean saveNewPhone(@ApiParam(required =true, name ="修改手机密保", value ="userId")String userId,String newPhone) {
        return employeeService.saveNewPhone(userId, newPhone);
    }
    /**
     * 修改备用邮箱
     */
    @ApiOperation(value = "id", httpMethod="GET", notes = "修改备用邮箱", response = ResultBean.class)
    @GetMapping("saveSpareMailbox")
    public ResultBean saveSpareMailbox(@ApiParam(required =true, name ="修改备用邮箱", value ="userId")String userId,String spareMailbox) {
        return employeeService.saveSpareMailbox(userId, spareMailbox);
    }






















   /* @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private QueryByExampleExecutor<Employee> queryByExampleExecutor;

    @Autowired
    EmployeeService employeeService;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;*/

    /**
     * 查询
     *
     * @return
     */
    /*@ApiOperation(value="获取用户列表", notes="")
    @GetMapping()
    public ResultBean list(AntdPage antdPage,String orgId,String name,  HttpServletRequest request) {
        Employee employee=this.getEmployeeInfo(request);
        return employeeService.queryList(antdPage,orgId,name,employee);
    }

    *//**
     * 查询
     *
     * @return
     *//*
    @ApiOperation(value="获取用户列表", notes="")
    @GetMapping("/queryall")
    public ResultBean queryall(AntdPage antdPage,HttpServletRequest request) {
        //Employee employee=this.getEmployeeInfo(request);
        Employee employee=new Employee();
        Organization o=new Organization();
       *//* o.setTreeParentIds("0");
        employee.setOrganization(o);*//*
        return employeeService.queryList(antdPage,null,null,employee);
    }


    @PostMapping("/resetPwd")
    public ResultBean rePwdEmp(@RequestBody  Employee employee){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        employeeService.rePwdEmp(employee);
        return resultBean;
    }

    @PostMapping("")
    public ResultBean create(@RequestBody Employee employee,  HttpServletRequest request){
       return  employeeService.saves(employee,request);

    }

    @PutMapping("")
    public ResultBean edit(@RequestBody Map map, HttpServletRequest request) {
        ResultBean resultBean = new ResultBean();
        try {
            Employee empOld = employeeRepository.findById(map.get("id").toString());
            BeanUtils.setBeanData(empOld,map);
            boolean contains = map.containsKey("enabled");    //判断是否包含指定的键值
            if (contains) {         //如果条件为真
               if("true".equals(map.get("enabled").toString())){
                  *//* empOld.setEnabled(true);*//*
               }else if("false".equals(map.get("enabled").toString())){
                   *//*empOld.setEnabled(false);*//*
               }
            }
            employeeRepository.saveAndFlush(empOld);
            //保存明细信息
            resultBean.setResultCode(ResultBean.SUCCESS);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }



    *//**
     * 删除
     * @param
     * @return
     *//*
    @DeleteMapping()
    public ResultBean deleteEmp(@RequestBody  Employee employee){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        String id=employee.getId();

        Employee employee1=employeeRepository.findOne(id);
       *//* List<Role> roleList = employee1.getRoles();*//*
       *//* if (roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                List<Employee> set = role.getEmployees();
                if (set != null && set.size() > 0) {
                    set.remove(employee1);
                    roleRepository.save(role);
                    continue;
                }

            }
        }*//*

        employeeRepository.delete(employee.getId());
        return resultBean;
    }

    @PatchMapping("")
    public Object patch( @RequestBody Employee employee){
         Employee savedEmployee =  employeeService.updateUser(employee);
            return new ApiResult().Add("employee", savedEmployee).Success();
    }

    @PatchMapping("toggleEnabled")
    @ApiOperation(value="启用、禁用用户", notes="启用、禁用employee")
    public Object disableUser(@RequestBody Employee employee){
        Employee disabledEmployee =  employeeService.toggleEnabled(employee);
        return new ApiResult().Add("employee", disabledEmployee).Success();
    }





    @GetMapping("myself")
    public Map<String,EmployeeMyself> getAuthenticatedUser(String token,HttpServletRequest request) {
        //String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        Employee employee = employeeRepository.findByUsername(username);
       *//* if(employee.getRoles()==null || employee.getRoles().size()==0){
            throw new ForbiddenException();
        }
        Set<String> roleNames= employee.getRoles().stream().map(role -> role.getName()).collect(Collectors.toSet());
        Set<String> visits=new HashSet<>();
        for(Role role: employee.getRoles()){
            visits.addAll(role.getAuthorities().stream().map(authority-> authority.getId()).collect(Collectors.toSet()));
        }*//*
        EmployeeMyself employeeMyself =new EmployeeMyself();
        employeeMyself.setId(employee.getId());
        *//*employeeMyself.setUsername(employee.getUsername());
        EmployeePermission employeePermission =new EmployeePermission();
        employeePermission.setRole(roleNames);
        employeePermission.setVisit(visits);*//*
        *//*employeeMyself.setPermissions(employeePermission);*//*
        return new ApiResult().Add("employee", employeeMyself).Success();
    }

    @GetMapping("/mobile/validate")
    public Object validateMobile(String mobile,String employeeId ){
        if(employeeRepository.findByMobile(mobile)==null){
            return new ApiResult().Add("status",true).Success();
        }else{
            if(employeeId!=null && employeeRepository.findByMobile(mobile).getId().equals(employeeId)){
                return new ApiResult().Add("status",true).Success();
            }else{
                return new ApiResult().Add("status",false).Success();
            }
        }
    }


    @GetMapping("/show")
    @ResponseBody
    public String show(){
        return "src/routes/core/index/login";
    }

    @ApiOperation(value="获取用户列表", notes="权限管理获取用户列表")
    @RequestMapping(value = "/queryByPage", method = RequestMethod.GET)
    public ResultBean queryByPage(@PageableDefault(value = 10, sort = { "id" }, direction = Sort.Direction.ASC) AntPageRequest pageRequest, Employee employee) {
        ResultBean resultBean = new ResultBean();
        Page<Employee> page=employeeRepository.findAll(pageRequest);
        List<Employee> list = page.getContent();
        List<EmployeeVo> vos = new ArrayList<>();
        if(list != null && list.size() > 0){
            for (Employee emp : list) {
                EmployeeVo vo = new EmployeeVo();
                vo = VOUtil.getEmployeeVo(emp);
                String roleName = "";
              *//*  List<Role> roles = emp.getRoles();*//*
               *//* if(roles != null && roles.size() > 0){
                    for(Role role : roles){
                        if(StringUtils.isNotEmpty(roleName)) {
                            roleName = roleName + "," + role.getName();
                        }else {
                            roleName = role.getName();
                        }
                    }
                }*//*
                vo.setRoleName(roleName);
                vos.add(vo);
            }
        }
        resultBean.setPage(pageRequest.getPage());
        resultBean.setPageSize(page.getSize());
        resultBean.setRows(vos);
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setTotal(page.getTotalElements());
        //       resultBean.setPage();
        return resultBean;
    }

    @ApiOperation(value="权限管理", notes="给用户赋角色权限", response = Employee.class)
    @PostMapping("/authRole")
    public ResultBean authRole(@RequestBody Map<String,String> map){
        String empId = map.get("empId");
        String roleId = map.get("roleId");
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.FAIL);
        String[] roleIds = null;
        if(StringUtils.isNotEmpty(roleId)){
            roleIds = roleId.split(",");
            if(StringUtils.isNotEmpty(empId)){
                Employee employee = employeeRepository.findById(empId);
                if(employee != null){
                    List<Role> roles = new ArrayList<>();
                    for (String str:roleIds){
                       *//* roles.addAll(roleRepository.findById(str));*//*
                    }
                   *//* employee.setRoles(roles);*//*
                    employeeRepository.save(employee);
                    resultBean.setResultCode(ResultBean.SUCCESS);
                }
            }
        }
        return resultBean;
    }


    *//**
     * 修改密码
     *
     * @param map
     * @param request
     * @return
     *//*
    @PostMapping(value = "resetPassword")
    public ResultBean resetPassword(@RequestBody Map<String,String> map,HttpServletRequest request){
        ResultBean resultBean=new ResultBean(ResultBean.SUCCESS);
        Employee employee=this.getEmployeeInfo(request);//获取当前登录人
        String password=map.get("password").toString();//获取输入的密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
       *//* if(encoder.matches(password,employee.getPassword())){
            String newPassword=map.get("newPassword").toString();//获取新输入的密码
            employee.setPassword(encoder.encode(newPassword));
            employeeRepository.save(employee);
            resultBean.setResultDesc("修改成功!");
        }else{
            resultBean.setResultCode(ResultBean.FAIL);
            resultBean.setResultDesc("原密码输入不正确!");
        }*//*
        return resultBean;
    }


    *//**
     * 获取登录人信息
     *
     * @param request
     * @return
     *//*
    @GetMapping(value = "getEmployeeInfo")
    public Employee getEmployeeInfo(HttpServletRequest request){
        String token=request.getHeader("token");
        String username = jwtTokenUtil.getUsernameFromToken(token);
        Employee employee = employeeRepository.findByUsername(username);
        return employee;
    }




    *//**
     * PC登出方法
     *
     * @param request
     * @param response
     * @return
     *//*
    @PostMapping(value = "/loginOut")
    public ResultBean getLoginOut(HttpServletRequest request, HttpServletResponse response) {
        String authToken=request.getHeader("token");

        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        //当前登录人
        Employee employee = employeeRepository.findById(jwtTokenUtil.getUserIdFromToken(authToken));
        Cookie[] cookies = request.getCookies();
        String token = "";
        if (null == cookies) {
            System.out.println("没有cookie==============");
        } else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("tokenHeader")) {
                    token = cookie.getValue();
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    System.out.println("被删除的cookie名字为:" + cookie.getName());
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        ResultBean resultBean = new ResultBean();
        resultBean.setResultCode(ResultBean.SUCCESS);
        return resultBean;
    }*/
    public static void main(String[] args) {

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.print(encoder.encode("123"));
    }


}
